package sch.frog.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
	/*
	 * MySql:
	 * driverClass=com.mysql.jdbc.Driver
	 * url=jdbc:mysql://localhost:3306/???(databaseName)
	 * username=root
	 * password=root
	 * 
	 * Oracle:
	 * driverClass=oracle.jdbc.driver.OracleDriver
	 * url=jdbc:oracle:thin:@192.168.191.128:1521:orcl
	 * username=scott
	 * password=tiger
	 * */
	private static String driverClass;
	
	private static String username;
	private static String password;
	private static String url;
	static{
		Properties prop = new Properties();
		try {
			prop.load(JDBCUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties"));	//加载配置文件
		} catch (IOException e) {
			throw new RuntimeException("can't found config file dbconfig.properties");
		}
		
		driverClass = prop.getProperty("driverClass");
		username =  prop.getProperty("username");
		password = prop.getProperty("password");
		url = prop.getProperty("url");
		
		try {
			Class.forName(driverClass);		//加载数据库驱动
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("can't load database driver");
		}
	}
	
	public static Connection getConnection() throws SQLException{
		Connection conn = DriverManager.getConnection(url, username, password);		//配置并获取连接
		return conn;
	}
	
	public static void close(ResultSet rs, Statement stat, Connection conn) throws SQLException {
		if(rs != null){
			rs.close();
		}
		if(stat != null){
			stat.close();
		}
		if(conn != null){
			conn.close();
		}
	}
}
